import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import '../../../../lib_basemodel/user/user.dart';
import '../../../../lib_runtime/logger.dart';
import '../../interface/chat_room_leaf_interface.dart';
import 'package:fixnum/fixnum.dart' as $fixnum;

class DoufengTacitModel extends ChatRoomChangeNotifier {
  BuildContext context;

  Timer? _timer;
  int autoDismissSec;
  VoidCallback? onAutoDismissCallback;
  late AnimationController _factorAnimationController;
  bool popAfterAutoDismiss = true;

  // TacitPush? tacitPush;
  // TacitAnswer? selectedAnswer;
  User? userFrom;
  User? userTo;

  // late MessageNotifierCallBack messageNotifierCallBack;

  DoufengTacitModel(
      {required this.context,
      required this.autoDismissSec,
      this.onAutoDismissCallback,
      this.popAfterAutoDismiss = true}) {
/*
    messageNotifierCallBack = (EMCustomMessageBody message) {
      if (message.params!["content"] == null) {
        return;
      }
      TacitPush tacitPush = TacitPush.create()
        ..mergeFromProto3Json(json.decode(message.params!["content"]!),
            ignoreUnknownFields: true);
      //判断message是否是想要的
      if (tacitPush == null || tacitPush.user == null||tacitPush.gs==null) {
        return;
      }
      this.tacitPush = tacitPush;
      getUser();
      if (tacitPush.hasAbort()) {
        RLog.i('------- 中止 ----------');
        Navigator.maybePop(context);
        DoufengTacitDialogManager.showInvitingRefuseDialog(context, tacitPush);
      }else if(tacitPush.hasInvitation()){
        RLog.i('------- 接受邀请 ----------');
        DoufengTacitDialogManager.showInvitingGsDialog(context,tacitPush,rootProxyModel.channel!.channelId);
      }else if(tacitPush.hasQuest()){
        RLog.i('------- 开始答题 ----------');
        Navigator.maybePop(context);
        // Navigator.popUntil(context, (ModalRoute.withName) => false);
        DoufengTacitDialogManager.showQuestionAnswerDialog(context,tacitPush,"question_answer_dialog");
      }else if(tacitPush.hasEnd()){
        RLog.i('------- 结束 ----------');
        // DoufengTacitDialogManager.show(rootNavigatorState.currentContext!);
      }
    };
    MessageNotifier.instance
        .registerCallback("TacitPush", messageNotifierCallBack);
    // autoDismiss();
    */
  }

  static tacitResponse(
      BuildContext context, bool accept, $fixnum.Int64 channelId) async {
    // var result = await TacitApi.instance
    //     .response(GsTacitResponse(accept: accept, channelId: channelId));
    // if (accept == true) {
    //   if (result.isSuccess) {
    //     showLoadingDialog(status: "请等待开始");
    //   }
    // } else {
    //   Navigator.pop(context);
    // }

    // if (!result.isSuccess) {
    //   dismissLoadingDialog();
    //   showToast('${result.errorMsg}');
    //   return;
    // }
    // dismissLoadingDialog();
  }

  tacitAnswer(int questIndex, int answerIndex) async {
    // var result = await TacitApi.instance.answer(
    //   AnswerTacitQuest(
    //     questIndex: questIndex,
    //     answerIndex: answerIndex,
    //     channelId: roomModel.channel!.channelId,
    //   ),
    // );
    // if(!result.isSuccess){
    //   showToast("回答问题出错：${result.errorMsg}");
    // }
  }

  getUser() async {
    // var resultFrom =await UserApi.instance.getUserInfoByUid(tacitPush!.user.toString());
    // var resultTo =await UserApi.instance.getUserInfoByUid(tacitPush!.gs.toString());
    // if(resultFrom.isSuccess){
    //   userFrom = resultFrom.data?.user;
    // }
    // if(resultTo.isSuccess){
    //   userTo = resultTo.data?.user;
    // }
    // notifyListeners();
  }

  @override
  void dispose() {
    super.dispose();

    RLog.d("当前堆栈");
    RLog.d(StackTrace.current);

    //反注册
    // MessageNotifier.instance
    //     .unRegisterCallback("TacitPush", messageNotifierCallBack);
  }

  @override
  onRootProxyModelCreated() {
    // currentBackgroundItem = rootProxyModel.backgroundAssetsList[0];
  }

  @override
  observeMessage(int messageId, data) {}

  AnimationController getAnimationController(TickerProvider vsync) {
    _factorAnimationController = AnimationController(
        vsync: vsync, duration: Duration(seconds: autoDismissSec))
      ..addListener(() {
        // notifyListeners();
      });
    _factorAnimationController.forward();
    return _factorAnimationController;
  }

  cancelTimer() {
    _timer?.cancel();
    _timer == null;
  }

  autoDismissFunc() {
    if (autoDismissSec > 0) {
      _timer = Timer.periodic(
        Duration(seconds: 1),
        (timer) {
          if (autoDismissSec <= 0) {
            cancelTimer();
            return;
          }
          autoDismissSec--;
          notifyListeners();
          if (autoDismissSec == 0) {
            onAutoDismissCallback?.call();
            if (popAfterAutoDismiss) {
              Navigator.pop(context);
            }
          }
        },
      );
    }
  }
}
